"""
Case Type   : 系统视图PG_PREPARED_STATEMENT
Case Name   : 兼容A库创建预备语句，查询函数返回正常
Create At   : 2023/12/14
Owner       : ningyali
Description :
    1.创建兼容A库
    2.切换到A库，创建预备语句
    3.使用PG_PREPARED_STATEMENT函数查询
    4.清理环境
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功，可查询到预备语句
    4.执行成功
History     :
"""

import os
import time
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class PgPreparedStatement43(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.db_name = 'db_prepare_43'
        self.pre_sql = 'prepare pre1 as select now();'
        self.q_sql = 'select * from pg_prepared_statement(0);\n' \
                     'select pg_prepared_statement(pg_current_sessid());'

    def test_1(self):
        text = 'step1:创建兼容A库; expect:执行成功'
        self.log.info(f'-----{text}-----')
        sql = f"drop database if exists {self.db_name};" \
            f"create database {self.db_name} dbcompatibility='A';"
        self.log.info(sql)
        res = self.pri_sh.execut_db_sql(sql)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, res,
                      f'执行失败：{text}')

        text = 'step2:切换到A库，创建预备语句; expect:执行成功'
        self.log.info(f'-----{text}-----')
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(self.pre_sql + 'select pg_sleep(3);', '',
                                   self.db_name,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text = 'step3:使用PG_PREPARED_STATEMENT函数查询; expect:执行成功，可查询到预备语句'
        self.log.info(f'-----{text}-----')
        res = self.pri_sh.execut_db_sql(self.q_sql, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.pre_sql, res, f'执行失败：{text}')

        text = '获取session1结果'
        self.log.info(f'-----{text}-----')
        session1.join(180)
        res1 = session1.get_result()
        self.log.info(f'res1:\n{res1}')
        self.assertIn('PREPARE', res1, f'执行失败：{text}')

    def tearDown(self):
        self.log.info('----run teardown----')
        text = 'step4:清理环境; expect:执行成功'
        self.log.info(f'-----{text}-----')
        sql = f'drop database if exists {self.db_name};'
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, res,
                      f'执行失败：{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
